define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'coursetable/classroomeplan/index',
                    add_url: 'coursetable/classroomeplan/add',
                    edit_url: 'coursetable/classroomeplan/edit',
                    multi_url: 'coursetable/classroomeplan/multi',
                    del_url: 'coursetable/classroomeplan/del',
                    table: 'fa_course_classroomeplan',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'id', //要使排序生效，在前面添加 weigh desc, 并且数据表weigh字段不能全为0,controller里$list=...->order前再添加->order("weigh desc")
                search: true,
                searchFields: ['classes_id'],
                searchPlaceholder: '请输入班名',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'table_id', title: '课程或项目' },
                        { field: 'classes_id', title: '班级' },
                        { field: 'ocation_id', title: '教学点' },
                        { field: 'week', title: '周几' },
                        { field: 'daytime', title: '时段' },
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                // {
                                //     name: 'detail',
                                //     classname: 'btn btn-xs btn-primary btn-click',
                                //     icon: 'fa fa-sitemap',
                                //     click: function (value, row, index) {
                                //         Backend.api.open('/adminht.php/dept/dept?relType=school&relId='+row.id+'&ref=addtabs', '组织结构2', {
                                //             max: true,
                                //             area: ['80%', '80%'],
                                //             //offset: ['0px', '0px'],
                                //             callback: function (data) {
                                //                 Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                //             }
                                //         });
                                //     }
                                // }
                            ]
                        }
                    ]
                ]
            });
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            Controller.api.bindevent();
            Controller.api.initTimeSchedule();
        },
        edit: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            Controller.api.bindevent();
            Controller.api.initTimeSchedule(true);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                // 在编辑模式下设置表单默认值
                Controller.api.setFormDefaults();
            },

            // 设置表单默认值
            setFormDefaults: function () {
                // 获取行数据
                var rowData = null;
                try {
                    if ($('#row').length > 0 && $('#row').val()) {
                        var rawData = $('#row').val();
                        console.log('原始行数据:', rawData);
                        rowData = JSON.parse(rawData);

                        // 如果是数组，取第一条记录作为默认值
                        if (Array.isArray(rowData) && rowData.length > 0) {
                            rowData = rowData[0];
                        }

                        console.log('解析后的行数据:', rowData);
                    }
                } catch (e) {
                    console.error('解析行数据失败:', e);
                    return;
                }

                if (!rowData) {
                    console.log('没有行数据，跳过默认值设置');
                    return;
                }

                // 设置表单字段默认值
                setTimeout(function () {
                    // 设置课程或项目
                    if (rowData.table_id) {
                        $('#c-table_id').val(rowData.table_id).trigger('change');
                        console.log('设置课程ID:', rowData.table_id);
                    }

                    // 设置班级
                    if (rowData.classes_id) {
                        $('#c-classes_id').val(rowData.classes_id).trigger('change');
                        console.log('设置班级ID:', rowData.classes_id);
                    }

                    // 设置教学点
                    if (rowData.ocation_id) {
                        $('#c-ocation_class').val(rowData.ocation_id).trigger('change');
                        console.log('设置教学点ID:', rowData.ocation_id);
                    }
                }, 500); // 延迟执行，确保选项已加载

                // 监听选项加载完成事件，重新设置默认值
                var retryCount = 0;
                var maxRetries = 10;

                function retrySetDefaults() {
                    retryCount++;

                    var tableOptions = $('#c-table_id option').length;
                    var classOptions = $('#c-classes_id option').length;
                    var ocationOptions = $('#c-ocation_class option').length;

                    console.log('检查选项加载状态:', {
                        retryCount: retryCount,
                        tableOptions: tableOptions,
                        classOptions: classOptions,
                        ocationOptions: ocationOptions
                    });

                    if ((tableOptions > 1 && classOptions > 1 && ocationOptions > 1) || retryCount >= maxRetries) {
                        // 选项已加载，设置默认值
                        if (rowData.table_id && $('#c-table_id').val() != rowData.table_id) {
                            $('#c-table_id').val(rowData.table_id).trigger('change');
                        }
                        if (rowData.classes_id && $('#c-classes_id').val() != rowData.classes_id) {
                            $('#c-classes_id').val(rowData.classes_id).trigger('change');
                        }
                        if (rowData.ocation_id && $('#c-ocation_class').val() != rowData.ocation_id) {
                            $('#c-ocation_class').val(rowData.ocation_id).trigger('change');
                        }

                        console.log('默认值设置完成');
                    } else {
                        // 继续等待
                        setTimeout(retrySetDefaults, 300);
                    }
                }

                // 开始重试设置默认值
                setTimeout(retrySetDefaults, 1000);
            },
            // 多时间段管理功能
            initTimeSchedule: function (isEdit) {
                var timeScheduleIndex = 0;
                var existingSchedules = [];

                // 从教学点获取周几和时段选项（按照原版逻辑）
                var weekOptions = [];
                var daytimeOptions = [];

                // 获取周几选项的函数
                function getWeekOptions() {
                    var $selectedOption = $("#c-ocation_class option:selected");
                    var weekdays = $selectedOption.attr("weekdays");

                    weekOptions = [{ value: '', text: '请选择周几' }];

                    console.log('获取周几选项:', weekdays); // 调试信息

                    if (weekdays && weekdays !== 'undefined' && weekdays !== '') {
                        var weekdayArray = weekdays.split(',');
                        var weekdayMap = {
                            '1': '周一', '2': '周二', '3': '周三', '4': '周四',
                            '5': '周五', '6': '周六', '7': '周日'
                        };

                        weekdayArray.forEach(function (day) {
                            day = day.trim();
                            if (weekdayMap[day]) {
                                weekOptions.push({ value: day, text: weekdayMap[day] });
                            }
                        });
                    } else {
                        // 如果没有从教学点获取到周几数据，使用默认的全部周几
                        console.log('使用默认周几选项');
                        var defaultWeekdays = ['1', '2', '3', '4', '5', '6', '7'];
                        var weekdayMap = {
                            '1': '周一', '2': '周二', '3': '周三', '4': '周四',
                            '5': '周五', '6': '周六', '7': '周日'
                        };

                        defaultWeekdays.forEach(function (day) {
                            weekOptions.push({ value: day, text: weekdayMap[day] });
                        });

                        // 如果是编辑模式，确保现有的周几值在选项中
                        if (isEdit && existingSchedules.length > 0) {
                            existingSchedules.forEach(function (schedule) {
                                if (schedule.week && !weekOptions.find(function (opt) { return opt.value === schedule.week; })) {
                                    var weekText = weekdayMap[schedule.week] || '周' + schedule.week;
                                    weekOptions.push({ value: schedule.week, text: weekText });
                                }
                            });
                        }
                    }

                    console.log('周几选项:', weekOptions); // 调试信息
                }

                // 获取时段选项的函数
                function getDaytimeOptions(selectedWeek) {
                    var scheduleData = $("#c-ocation_class option:selected").attr("schedule_data");
                    var already_schedule = $("#c-ocation_class option:selected").attr("already_schedule");
                    var disable_week_time = $("#c-ocation_class option:selected").attr("disable_week_time");
                    var ocation = $("#c-ocation_class option:selected").val();

                    daytimeOptions = [{ value: '', text: '请选择时段' }];

                    console.log('获取时段选项:', {
                        scheduleData: scheduleData,
                        selectedWeek: selectedWeek,
                        ocation: ocation
                    });

                    if (scheduleData && selectedWeek && ocation) {
                        try {
                            var scheduleArray = JSON.parse(scheduleData);
                            var already_scheduleArray = already_schedule ? JSON.parse(already_schedule) : {};
                            var disable_week_timeArray = disable_week_time ? JSON.parse(disable_week_time) : {};

                            // 获取当前记录ID（用于排除自己的占用）
                            var currentId = 0;
                            if (isEdit && $('#row').length > 0) {
                                try {
                                    var firstParse = JSON.parse($('#row').val());
                                    if (typeof firstParse === 'string') {
                                        var rowData = JSON.parse(firstParse);
                                    } else {
                                        var rowData = firstParse;
                                    }

                                    if (Array.isArray(rowData) && rowData.length > 0) {
                                        currentId = rowData[0].id || 0;
                                    } else if (rowData.id) {
                                        currentId = rowData.id;
                                    }
                                } catch (e) {
                                    console.log('获取当前记录ID失败:', e);
                                }
                            }

                            for (let i = 0; i < scheduleArray.length; i++) {
                                const schedule = scheduleArray[i];
                                var optionText = schedule.start_time + '-' + schedule.end_time;
                                var optionValue = optionText;
                                var disabled = false;

                                // 使用原有的简单检测逻辑，避免大量AJAX请求
                                if (already_scheduleArray[ocation] && already_scheduleArray[ocation][selectedWeek]) {
                                    if (already_scheduleArray[ocation][selectedWeek].indexOf(optionText) !== -1) {
                                        // 如果是编辑模式，需要检查是否是当前记录占用的
                                        var isCurrentRecordOccupied = false;
                                        if (isEdit && existingSchedules.length > 0) {
                                            existingSchedules.forEach(function (schedule) {
                                                if (schedule.week === selectedWeek && schedule.daytime === optionValue) {
                                                    isCurrentRecordOccupied = true;
                                                }
                                            });
                                        }

                                        if (!isCurrentRecordOccupied) {
                                            optionText += '(已被占用)';
                                            disabled = true;
                                        } else {
                                            optionText += '(当前记录)';
                                        }
                                    }
                                }

                                // 检查是否被禁用
                                if (disable_week_timeArray[ocation] && disable_week_timeArray[ocation][selectedWeek]) {
                                    if (disable_week_timeArray[ocation][selectedWeek].indexOf(optionText) !== -1) {
                                        optionText += ' (该时间点禁用)';
                                        disabled = true;
                                    }
                                }

                                daytimeOptions.push({
                                    value: optionValue,
                                    text: optionText,
                                    disabled: disabled
                                });
                            }

                            // 注意：异步更新将在选择器填充后进行
                        } catch (e) {
                            console.error('解析时段数据失败:', e);
                        }
                    } else if (selectedWeek) {
                        // 如果没有从教学点获取到时段数据，使用默认时段
                        console.log('使用默认时段选项');
                        var defaultDaytimes = [
                            { value: '08:30-11:30', text: '上午 (08:30-11:30)' },
                            { value: '12:00-13:30', text: '中午 (12:00-13:30)' },
                            { value: '14:00-17:00', text: '下午 (14:00-17:00)' },
                            { value: '19:00-21:30', text: '晚上 (19:00-21:30)' }
                        ];

                        defaultDaytimes.forEach(function (option) {
                            daytimeOptions.push(option);
                        });

                        // 如果是编辑模式，确保现有的时段值在选项中
                        if (isEdit && existingSchedules.length > 0) {
                            existingSchedules.forEach(function (schedule) {
                                if (schedule.daytime && schedule.week === selectedWeek) {
                                    var existingOption = daytimeOptions.find(function (opt) {
                                        return opt.value === schedule.daytime;
                                    });
                                    if (!existingOption) {
                                        daytimeOptions.push({
                                            value: schedule.daytime,
                                            text: schedule.daytime + ' (现有数据)',
                                            disabled: false
                                        });
                                    }
                                }
                            });
                        }
                    }

                    console.log('时段选项:', daytimeOptions);
                }

                // 如果是编辑模式，解析现有数据
                if (isEdit) {
                    try {
                        var rowData = null;

                        // 尝试从隐藏字段获取数据
                        if ($('#row').length > 0 && $('#row').val()) {
                            var rawValue = $('#row').val();
                            console.log('隐藏字段原始值:', rawValue);

                            // 处理HTML转义的JSON字符串
                            var unescapedValue = rawValue
                                .replace(/&quot;/g, '"')
                                .replace(/&amp;/g, '&')
                                .replace(/&lt;/g, '<')
                                .replace(/&gt;/g, '>')
                                .replace(/&#039;/g, "'");

                            console.log('反转义后的值:', unescapedValue);

                            try {
                                var firstParse = JSON.parse(unescapedValue);
                                console.log('第一次解析结果类型:', typeof firstParse);

                                // 处理双重JSON编码问题
                                if (typeof firstParse === 'string') {
                                    console.log('检测到双重JSON编码，进行第二次解析');
                                    rowData = JSON.parse(firstParse);
                                } else {
                                    rowData = firstParse;
                                }
                            } catch (e) {
                                console.log('第一次解析失败，尝试直接解析:', e);
                                try {
                                    rowData = JSON.parse(rawValue);
                                } catch (e2) {
                                    console.log('第二次解析也失败:', e2);
                                }
                            }
                        }

                        // 如果没有隐藏字段数据，尝试从表单字段获取
                        if (!rowData) {
                            var weekVal = $('input[name="row[week]"]').val() || $('select[name="row[week]"]').val();
                            var daytimeVal = $('input[name="row[daytime]"]').val() || $('select[name="row[daytime]"]').val();
                            var idVal = $('input[name="row[id]"]').val();

                            if (weekVal || daytimeVal) {
                                rowData = {
                                    week: weekVal,
                                    daytime: daytimeVal,
                                    id: idVal
                                };
                            }
                        }

                        console.log('编辑模式 - 原始数据:', rowData);
                        console.log('编辑模式 - 数据类型:', typeof rowData, Array.isArray(rowData));
                        console.log('编辑模式 - 数据构造函数:', rowData.constructor.name);
                        console.log('编辑模式 - 是否为数组（详细）:', Object.prototype.toString.call(rowData));

                        if (rowData) {
                            // 检查是否是数组（多记录）还是单个对象（单记录）
                            // 使用多种方式检查数组
                            var isArray = Array.isArray(rowData) ||
                                Object.prototype.toString.call(rowData) === '[object Array]' ||
                                (rowData.constructor && rowData.constructor.name === 'Array') ||
                                (typeof rowData === 'object' && typeof rowData.length === 'number' && rowData.length >= 0);

                            console.log('数组检查结果:', isArray);

                            if (isArray) {
                                // 多记录模式 - 每个记录都是独立的时间段
                                console.log('多记录模式，记录数量:', rowData.length);
                                rowData.forEach(function (record, index) {
                                    console.log('记录', index, ':', record);
                                    console.log('周几:', record.week, '时段:', record.daytime);

                                    // 更宽松的条件检查
                                    if (record.week !== undefined && record.daytime !== undefined &&
                                        record.week !== null && record.daytime !== null &&
                                        record.week.toString().trim() !== '' && record.daytime.toString().trim() !== '') {
                                        var scheduleItem = {
                                            week: record.week.toString().trim(),
                                            daytime: record.daytime.toString().trim(),
                                            id: record.id
                                        };
                                        existingSchedules.push(scheduleItem);
                                        console.log('成功添加时间段:', scheduleItem);
                                    } else {
                                        console.log('记录', index, '数据不完整，跳过');
                                    }
                                });
                            } else if (rowData.week !== undefined && rowData.daytime !== undefined) {
                                // 单记录模式 - 可能包含逗号分隔的多个时间段
                                console.log('单记录模式');
                                console.log('原始周几:', rowData.week, '原始时段:', rowData.daytime);

                                var weeks = rowData.week.toString().split(',');
                                var daytimes = rowData.daytime.toString().split(',');

                                console.log('解析的周几:', weeks);
                                console.log('解析的时段:', daytimes);

                                // 确保周几和时段数量一致
                                var maxLength = Math.max(weeks.length, daytimes.length);
                                for (var i = 0; i < maxLength; i++) {
                                    var week = (weeks[i] || '').trim();
                                    var daytime = (daytimes[i] || '').trim();

                                    console.log('处理时间段', i, ':', { week: week, daytime: daytime });

                                    if (week && daytime) {
                                        existingSchedules.push({
                                            week: week,
                                            daytime: daytime,
                                            id: rowData.id
                                        });
                                    } else {
                                        console.log('时间段', i, '数据不完整，跳过');
                                    }
                                }
                            } else {
                                console.log('数据格式不符合预期，尝试其他解析方式');
                                // 尝试其他可能的字段名
                                var possibleWeekFields = ['week', 'Week', 'WEEK', 'weekday'];
                                var possibleDaytimeFields = ['daytime', 'Daytime', 'DAYTIME', 'time_slot'];

                                var foundWeek = null, foundDaytime = null;

                                for (var i = 0; i < possibleWeekFields.length; i++) {
                                    if (rowData[possibleWeekFields[i]] !== undefined) {
                                        foundWeek = rowData[possibleWeekFields[i]];
                                        console.log('找到周几字段:', possibleWeekFields[i], '=', foundWeek);
                                        break;
                                    }
                                }

                                for (var i = 0; i < possibleDaytimeFields.length; i++) {
                                    if (rowData[possibleDaytimeFields[i]] !== undefined) {
                                        foundDaytime = rowData[possibleDaytimeFields[i]];
                                        console.log('找到时段字段:', possibleDaytimeFields[i], '=', foundDaytime);
                                        break;
                                    }
                                }

                                if (foundWeek && foundDaytime) {
                                    existingSchedules.push({
                                        week: foundWeek.toString().trim(),
                                        daytime: foundDaytime.toString().trim(),
                                        id: rowData.id
                                    });
                                }
                            }
                        }

                        console.log('解析后的现有时间段:', existingSchedules);

                        // 检查解析结果
                        var hasValidData = false;
                        for (var i = 0; i < existingSchedules.length; i++) {
                            if (existingSchedules[i].week && existingSchedules[i].daytime) {
                                hasValidData = true;
                                break;
                            }
                        }

                        if (!hasValidData) {
                            console.log('解析到的数据无效或为空，尝试通过AJAX获取');
                            // 清空无效数据
                            existingSchedules = [];
                            Controller.api.loadExistingSchedules();
                        } else {
                            console.log('成功解析到', existingSchedules.length, '个有效时间段');
                        }
                    } catch (e) {
                        console.error('解析现有数据失败:', e);
                        // 如果解析失败，尝试通过AJAX获取
                        Controller.api.loadExistingSchedules();
                    }
                }

                // 如果没有现有数据，添加一个空的时间段（仅在有教学点时）
                if (existingSchedules.length === 0) {
                    existingSchedules.push({ week: '', daytime: '' });
                }

                // 创建时间段项目
                function createTimeScheduleItem(index, weekValue, daytimeValue) {
                    weekValue = weekValue || '';
                    daytimeValue = daytimeValue || '';

                    console.log('创建时间段项目:', { index: index, weekValue: weekValue, daytimeValue: daytimeValue });

                    // 获取当前的选项数据
                    getWeekOptions();

                    var weekSelect = '<select class="form-control week-select" name="schedules[' + index + '][week]" style="width: 45%; display: inline-block;">';
                    weekOptions.forEach(function (option) {
                        var selected = option.value === weekValue ? 'selected' : '';
                        weekSelect += '<option value="' + option.value + '" ' + selected + '>' + option.text + '</option>';
                    });
                    weekSelect += '</select>';

                    // 如果有选中的周几，获取对应的时段选项
                    if (weekValue) {
                        getDaytimeOptions(weekValue);
                    } else {
                        daytimeOptions = [{ value: '', text: '请先选择周几' }];
                    }

                    // 如果是编辑模式且有现有的时段值，确保它在选项中
                    if (isEdit && daytimeValue && daytimeOptions.length === 1) {
                        // 添加当前值作为选项
                        daytimeOptions.push({
                            value: daytimeValue,
                            text: daytimeValue,
                            disabled: false
                        });
                    }

                    var daytimeSelect = '<select class="form-control daytime-select" name="schedules[' + index + '][daytime]" style="width: 45%; display: inline-block; margin-left: 2%;">';
                    daytimeOptions.forEach(function (option) {
                        var selected = option.value === daytimeValue ? 'selected' : '';
                        var disabled = option.disabled ? 'disabled' : '';
                        daytimeSelect += '<option value="' + option.value + '" ' + selected + ' ' + disabled + '>' + option.text + '</option>';
                    });
                    daytimeSelect += '</select>';

                    var removeBtn = '<button type="button" class="btn btn-danger btn-sm remove-schedule" style="margin-left: 2%;">' +
                        '<i class="fa fa-minus"></i></button>';

                    var itemHtml = '<div class="time-schedule-item" style="margin-bottom: 10px;" data-index="' + index + '">' +
                        weekSelect + daytimeSelect + removeBtn +
                        '</div>';

                    // 如果有选中的周几，异步更新时段占用详情
                    if (weekValue) {
                        setTimeout(function() {
                            var $item = $('.time-schedule-item[data-index="' + index + '"]');
                            var $daytimeSelect = $item.find('.daytime-select');

                            if ($daytimeSelect.length > 0) {
                                var ocation = $("#c-ocation_class").val();
                                var currentId = 0;

                                if (isEdit && $('#row').length > 0) {
                                    try {
                                        var firstParse = JSON.parse($('#row').val());
                                        if (typeof firstParse === 'string') {
                                            var rowData = JSON.parse(firstParse);
                                        } else {
                                            var rowData = firstParse;
                                        }

                                        if (Array.isArray(rowData) && rowData.length > 0) {
                                            currentId = rowData[0].id || 0;
                                        } else if (rowData.id) {
                                            currentId = rowData.id;
                                        }
                                    } catch (e) {
                                        console.log('获取当前记录ID失败:', e);
                                    }
                                }

                                console.log('createTimeScheduleItem异步更新参数:', {
                                    ocation: ocation,
                                    weekValue: weekValue,
                                    currentId: currentId,
                                    existingSchedules: existingSchedules,
                                    daytimeSelectLength: $daytimeSelect.length
                                });

                                Controller.api.updateTimeSlotOccupancyInfo(ocation, weekValue, currentId, $daytimeSelect, existingSchedules, isEdit);
                            }
                        }, 200);
                    }

                    return itemHtml;
                }

                // 初始化现有时间段
                function initTimeSchedules() {
                    var container = $('#time-schedule-container');
                    if (container.length === 0) return;

                    container.empty();

                    console.log('初始化时间段:', {
                        isEdit: isEdit,
                        existingSchedules: existingSchedules,
                        hasOcation: $('#c-ocation_class').val()
                    });

                    // 如果是编辑模式且有现有数据，直接显示
                    if (isEdit && existingSchedules.length > 0) {
                        existingSchedules.forEach(function (schedule, index) {
                            console.log('创建时间段项目:', index, schedule);
                            container.append(createTimeScheduleItem(index, schedule.week, schedule.daytime));
                            timeScheduleIndex = index + 1;
                        });
                        return;
                    }

                    // 如果是编辑模式但没有现有数据，等待数据加载
                    if (isEdit && existingSchedules.length === 0) {
                        container.html('<div class="alert alert-info">正在加载现有时间安排...</div>');
                        return;
                    }

                    // 如果没有现有数据且没有选择教学点，显示提示
                    if (existingSchedules.length === 0 && !$('#c-ocation_class').val()) {
                        container.html('<div class="alert alert-info">请先选择教学点，然后添加时间段</div>');
                        return;
                    }

                    // 其他情况，正常显示时间段
                    if (existingSchedules.length > 0) {
                        existingSchedules.forEach(function (schedule, index) {
                            container.append(createTimeScheduleItem(index, schedule.week, schedule.daytime));
                            timeScheduleIndex = index + 1;
                        });
                    } else {
                        // 添加一个空的时间段
                        container.append(createTimeScheduleItem(0, '', ''));
                        timeScheduleIndex = 1;
                    }
                }

                // 重新初始化时间段（供外部调用）
                Controller.api.initTimeSchedules = function () {
                    initTimeSchedules();
                };

                // 刷新时间段事件
                $(document).off('click', '#refresh-time-schedule').on('click', '#refresh-time-schedule', function () {
                    console.log('手动刷新时间段');
                    Controller.api.initTimeSchedules();
                });

                // 添加时间段事件
                $(document).off('click', '#add-time-schedule').on('click', '#add-time-schedule', function () {
                    var container = $('#time-schedule-container');
                    if (container.length === 0) return;

                    // 检查是否已选择教学点
                    if (!$('#c-ocation_class').val()) {
                        if (typeof layer !== 'undefined') {
                            layer.msg('请先选择教学点');
                        } else {
                            alert('请先选择教学点');
                        }
                        return;
                    }

                    // 移除提示信息
                    container.find('.alert-info').remove();

                    container.append(createTimeScheduleItem(timeScheduleIndex, '', ''));
                    timeScheduleIndex++;
                });

                // 删除时间段事件
                $(document).off('click', '.remove-schedule').on('click', '.remove-schedule', function () {
                    var item = $(this).closest('.time-schedule-item');
                    var container = $('#time-schedule-container');

                    // 至少保留一个时间段
                    if (container.find('.time-schedule-item').length > 1) {
                        item.remove();
                        // 删除后重新检查冲突
                        Controller.api.checkTimeConflict();
                    } else {
                        if (typeof layer !== 'undefined') {
                            layer.msg('至少需要保留一个时间段');
                        } else {
                            alert('至少需要保留一个时间段');
                        }
                    }
                });

                // 监听周几选择变化，更新时段选项
                $(document).off('change', '.week-select').on('change', '.week-select', function () {
                    var $this = $(this);
                    var selectedWeek = $this.val();
                    var $daytimeSelect = $this.siblings('.daytime-select');

                    // 更新时段选项
                    getDaytimeOptions(selectedWeek);

                    // 重新填充时段选项
                    $daytimeSelect.empty();
                    daytimeOptions.forEach(function (option) {
                        var disabled = option.disabled ? 'disabled' : '';
                        $daytimeSelect.append('<option value="' + option.value + '" ' + disabled + '>' + option.text + '</option>');
                    });

                    // 异步更新时段占用详情信息
                    var ocation = $("#c-ocation_class").val();
                    var currentId = 0;
                    if (isEdit && $('#row').length > 0) {
                        try {
                            var firstParse = JSON.parse($('#row').val());
                            if (typeof firstParse === 'string') {
                                var rowData = JSON.parse(firstParse);
                            } else {
                                var rowData = firstParse;
                            }

                            if (Array.isArray(rowData) && rowData.length > 0) {
                                currentId = rowData[0].id || 0;
                            } else if (rowData.id) {
                                currentId = rowData.id;
                            }
                        } catch (e) {
                            console.log('获取当前记录ID失败:', e);
                        }
                    }

                    // 延迟调用异步更新，确保DOM已更新
                    setTimeout(function () {
                        Controller.api.updateTimeSlotOccupancyInfo(ocation, selectedWeek, currentId, $daytimeSelect, existingSchedules, isEdit);
                    }, 100);

                    // 延迟检查冲突
                    clearTimeout(Controller.api.conflictCheckTimer);
                    Controller.api.conflictCheckTimer = setTimeout(function () {
                        Controller.api.checkTimeConflict();
                    }, 500);
                });

                // 监听时段选择变化
                $(document).off('change', '.daytime-select').on('change', '.daytime-select', function () {
                    // 延迟检查，避免频繁请求
                    clearTimeout(Controller.api.conflictCheckTimer);
                    Controller.api.conflictCheckTimer = setTimeout(function () {
                        Controller.api.checkTimeConflict();
                    }, 500);
                });

                // 监听教学点选项加载完成
                var ocationObserver = new MutationObserver(function (mutations) {
                    mutations.forEach(function (mutation) {
                        if (mutation.type === 'childList' && mutation.target.id === 'c-ocation_class') {
                            console.log('教学点选项已更新');
                            // 如果是编辑模式且有现有数据，重新初始化
                            if (isEdit && existingSchedules.length > 0) {
                                setTimeout(function () {
                                    initTimeSchedules();
                                }, 100);
                            }
                        }
                    });
                });

                // 开始观察教学点选择框的变化
                var ocationSelect = document.getElementById('c-ocation_class');
                if (ocationSelect) {
                    ocationObserver.observe(ocationSelect, {
                        childList: true,
                        subtree: true
                    });
                }

                // 监听教学点变化，重新初始化所有时间段
                $(document).off('change', '#c-ocation_class').on('change', '#c-ocation_class', function () {
                    var container = $('#time-schedule-container');
                    var selectedOcation = $(this).val();

                    if (!selectedOcation) {
                        // 如果没有选择教学点，清空并显示提示
                        container.html('<div class="alert alert-info">请先选择教学点，然后添加时间段</div>');
                        return;
                    }

                    // 移除提示信息
                    container.find('.alert-info').remove();

                    // 重新初始化所有时间段项目
                    $('.time-schedule-item').each(function () {
                        var $item = $(this);
                        var index = $item.data('index');

                        // 重新创建该项目（清空选择）
                        var newItem = createTimeScheduleItem(index, '', '');
                        $item.replaceWith(newItem);
                    });

                    // 如果没有时间段项目，添加一个空的
                    if ($('.time-schedule-item').length === 0) {
                        container.append(createTimeScheduleItem(0, '', ''));
                        timeScheduleIndex = 1;
                    }
                });

                // 表单提交前处理数据
                $('form').off('submit.timeSchedule').on('submit.timeSchedule', function (e) {
                    var weeks = [];
                    var daytimes = [];
                    var hasEmpty = false;

                    $('.time-schedule-item').each(function () {
                        var week = $(this).find('.week-select').val();
                        var daytime = $(this).find('.daytime-select').val();

                        if (!week || !daytime) {
                            hasEmpty = true;
                            return false;
                        }

                        weeks.push(week);
                        daytimes.push(daytime);
                    });

                    if (hasEmpty) {
                        if (typeof layer !== 'undefined') {
                            layer.msg('请完整填写所有时间段');
                        } else {
                            alert('请完整填写所有时间段');
                        }
                        e.preventDefault();
                        return false;
                    }

                    // 移除之前添加的隐藏字段
                    $(this).find('input[name="row[week]"], input[name="row[daytime]"]').remove();

                    // 创建隐藏字段传递数据
                    $('<input>').attr({
                        type: 'hidden',
                        name: 'row[week]',
                        value: weeks.join(',')
                    }).appendTo(this);

                    $('<input>').attr({
                        type: 'hidden',
                        name: 'row[daytime]',
                        value: daytimes.join(',')
                    }).appendTo(this);
                });

                // 等待教学点数据加载完成后初始化
                function waitForOcationData() {
                    var retryCount = 0;
                    var maxRetries = 30; // 增加重试次数

                    function checkAndInit() {
                        retryCount++;

                        // 检查教学点选项是否已加载
                        var ocationOptions = $('#c-ocation_class option').length;
                        var hasOcation = $('#c-ocation_class').val();

                        console.log('检查教学点数据:', {
                            retryCount: retryCount,
                            ocationOptions: ocationOptions,
                            hasOcation: hasOcation,
                            isEdit: isEdit,
                            existingSchedulesCount: existingSchedules.length
                        });

                        // 如果是编辑模式，优先处理现有数据
                        if (isEdit) {
                            if (existingSchedules.length > 0 && hasOcation) {
                                // 有现有数据且教学点已选中，直接初始化
                                initTimeSchedules();
                                return;
                            } else if (existingSchedules.length > 0 && retryCount <= 15) {
                                // 有现有数据但教学点未选中，等待教学点加载
                                setTimeout(checkAndInit, 400);
                                return;
                            } else if (existingSchedules.length === 0 && retryCount <= 10) {
                                // 没有现有数据但重试次数较少，继续等待数据解析
                                setTimeout(checkAndInit, 300);
                                return;
                            }
                            // 如果重试多次仍无数据，尝试通过AJAX加载
                            // （loadExistingSchedules已在数据解析失败时调用）
                        }

                        // 检查教学点数据是否已加载
                        if (ocationOptions > 1 || retryCount >= maxRetries) {
                            // 教学点数据已加载或达到最大重试次数
                            if (!hasOcation && !isEdit && existingSchedules.length === 0) {
                                // 如果是添加模式且没有选择教学点且没有现有数据，显示提示
                                $('#time-schedule-container').html('<div class="alert alert-info">请先选择教学点，然后添加时间段</div>');
                            } else {
                                // 初始化时间段
                                initTimeSchedules();
                            }
                        } else {
                            // 继续等待
                            setTimeout(checkAndInit, 200);
                        }
                    }

                    checkAndInit();
                }

                // 全局调试函数
                window.refreshTimeSchedule = function () {
                    console.log('全局刷新时间段');
                    if (typeof Controller !== 'undefined' && Controller.api && Controller.api.initTimeSchedules) {
                        Controller.api.initTimeSchedules();
                    } else {
                        console.error('Controller.api.initTimeSchedules 不可用');
                    }
                };

                // 强制重新加载数据的函数
                window.forceReloadData = function () {
                    console.log('强制重新加载数据');

                    // 直接重新调用initTimeSchedule来重新解析数据
                    if (typeof Controller !== 'undefined' && Controller.api && Controller.api.initTimeSchedule) {
                        console.log('重新调用initTimeSchedule');
                        Controller.api.initTimeSchedule(true);
                    } else {
                        console.log('Controller.api.initTimeSchedule不可用，尝试手动处理');

                        // 手动解析和显示数据
                        var schedules = [];
                        try {
                            var rowElement = $('#row');
                            if (rowElement.length > 0 && rowElement.val()) {
                                var rawValue = rowElement.val();

                                // 处理HTML转义
                                var unescapedValue = rawValue
                                    .replace(/&quot;/g, '"')
                                    .replace(/&amp;/g, '&')
                                    .replace(/&lt;/g, '<')
                                    .replace(/&gt;/g, '>')
                                    .replace(/&#039;/g, "'");

                                var rowData = JSON.parse(unescapedValue);
                                console.log('手动解析的数据:', rowData);

                                if (Array.isArray(rowData)) {
                                    rowData.forEach(function (record) {
                                        if (record.week && record.daytime) {
                                            schedules.push({
                                                week: record.week.toString().trim(),
                                                daytime: record.daytime.toString().trim(),
                                                id: record.id
                                            });
                                        }
                                    });
                                }
                            }
                        } catch (e) {
                            console.log('手动解析失败:', e);
                        }

                        console.log('手动解析完成，共', schedules.length, '个时间段');

                        // 手动创建时间段显示
                        if (schedules.length > 0) {
                            var container = $('#time-schedule-container');
                            container.empty();

                            schedules.forEach(function (schedule, index) {
                                console.log('手动创建时间段', index, ':', schedule);
                                // 这里需要调用createTimeScheduleItem，但它在函数作用域内
                                // 暂时显示简单的信息
                                var weekMap = { '1': '周一', '2': '周二', '3': '周三', '4': '周四', '5': '周五', '6': '周六', '7': '周日' };
                                var weekText = weekMap[schedule.week] || '周' + schedule.week;
                                container.append('<div class="alert alert-success">时间段 ' + (index + 1) + ': ' + weekText + ' ' + schedule.daytime + '</div>');
                            });
                        }
                    }
                };

                // 检查页面数据状态的调试函数
                window.checkPageData = function () {
                    console.log('=== 页面数据检查 ===');

                    // 检查隐藏字段
                    var rowElement = $('#row');
                    console.log('隐藏字段存在:', rowElement.length > 0);
                    if (rowElement.length > 0) {
                        console.log('隐藏字段值:', rowElement.val());
                        try {
                            var parsedData = JSON.parse(rowElement.val());
                            console.log('解析后的数据:', parsedData);
                            console.log('数据类型:', typeof parsedData, Array.isArray(parsedData));
                        } catch (e) {
                            console.log('解析失败:', e);
                        }
                    }

                    // 检查表单字段
                    console.log('表单字段值:');
                    console.log('- 课程ID:', $('#c-table_id').val());
                    console.log('- 班级ID:', $('#c-classes_id').val());
                    console.log('- 教学点ID:', $('#c-ocation_class').val());

                    // 检查选项数量
                    console.log('选项数量:');
                    console.log('- 课程选项:', $('#c-table_id option').length);
                    console.log('- 班级选项:', $('#c-classes_id option').length);
                    console.log('- 教学点选项:', $('#c-ocation_class option').length);

                    // 检查时间段容器
                    console.log('时间段容器:', $('#time-schedule-container').length > 0);
                    console.log('时间段项目数量:', $('.time-schedule-item').length);

                    console.log('=== 检查完成 ===');
                };

                // 直接测试AJAX请求的函数
                window.testAjaxRequest = function() {
                    console.log('=== 直接测试AJAX请求 ===');

                    $.ajax({
                        url: 'coursetable/classroomeplan/getTimeSlotOccupancy',
                        type: 'POST',
                        data: {
                            ocation_id: '423',
                            week: '2',
                            daytime: '15:15-16:45',
                            current_id: 0
                        },
                        success: function(response) {
                            console.log('AJAX请求成功:', response);
                        },
                        error: function(xhr, status, error) {
                            console.log('AJAX请求失败:', {
                                status: status,
                                error: error,
                                responseText: xhr.responseText
                            });
                        }
                    });
                };

                // 手动测试异步更新的函数
                window.testAsyncUpdate = function() {
                    console.log('=== 手动测试异步更新 ===');

                    var $firstSelect = $('.daytime-select').first();
                    var $firstItem = $firstSelect.closest('.time-schedule-item');
                    var weekValue = $firstItem.find('.week-select').val();
                    var ocation = $("#c-ocation_class").val();

                    console.log('测试参数:', {
                        weekValue: weekValue,
                        ocation: ocation,
                        selectLength: $firstSelect.length,
                        existingSchedules: existingSchedules
                    });

                    if (weekValue && ocation && $firstSelect.length > 0) {
                        Controller.api.updateTimeSlotOccupancyInfo(ocation, weekValue, 0, $firstSelect, existingSchedules, true);
                    } else {
                        console.log('测试条件不满足');
                    }
                };

                // 调试函数
                window.debugTimeSchedule = function () {
                    console.log('=== 时间段调试信息 ===');
                    console.log('isEdit:', isEdit);
                    console.log('existingSchedules:', existingSchedules);
                    console.log('weekOptions:', weekOptions);
                    console.log('daytimeOptions:', daytimeOptions);
                    console.log('教学点值:', $('#c-ocation_class').val());
                    console.log('教学点选项数量:', $('#c-ocation_class option').length);
                    console.log('时间段容器:', $('#time-schedule-container').html());

                    if ($('#row').length > 0) {
                        try {
                            var rowData = JSON.parse($('#row').val());
                            console.log('原始行数据:', rowData);
                        } catch (e) {
                            console.log('解析行数据失败:', e);
                        }
                    }
                };

                // 初始化
                setTimeout(waitForOcationData, 100);
            },

            // 加载现有的时间安排数据
            loadExistingSchedules: function () {
                // 获取当前记录的ID
                var currentId = null;

                // 尝试从URL参数获取ID
                var urlParams = new URLSearchParams(window.location.search);
                currentId = urlParams.get('ids');

                // 如果URL中没有，尝试从表单字段获取
                if (!currentId) {
                    currentId = $('input[name="row[id]"]').val();
                }

                // 如果还是没有，尝试从隐藏字段获取
                if (!currentId && $('#row').length > 0) {
                    try {
                        var rowData = JSON.parse($('#row').val());
                        if (Array.isArray(rowData) && rowData.length > 0) {
                            currentId = rowData[0].id;
                        } else if (rowData.id) {
                            currentId = rowData.id;
                        }
                    } catch (e) {
                        console.error('获取记录ID失败:', e);
                    }
                }

                console.log('尝试加载现有时间安排，记录ID:', currentId);

                if (!currentId) {
                    console.log('无法获取记录ID，跳过加载现有时间安排');
                    return;
                }

                // 发送AJAX请求获取该记录的所有时间安排
                $.ajax({
                    url: 'coursetable/classroomeplan/getSchedulesByRecord',
                    type: 'POST',
                    data: {
                        record_id: currentId
                    },
                    success: function (response) {
                        console.log('获取现有时间安排响应:', response);

                        if (response.code === 1 && response.data && response.data.length > 0) {
                            console.log('服务器返回数据:', response.data);

                            // 清空现有数据
                            existingSchedules = [];

                            // 添加获取到的时间安排
                            response.data.forEach(function (record, index) {
                                console.log('处理服务器记录', index, ':', record);
                                if (record.week && record.daytime) {
                                    existingSchedules.push({
                                        week: record.week.toString().trim(),
                                        daytime: record.daytime.toString().trim(),
                                        id: record.id
                                    });
                                    console.log('添加时间段:', {
                                        week: record.week.toString().trim(),
                                        daytime: record.daytime.toString().trim()
                                    });
                                } else {
                                    console.log('服务器记录', index, '数据不完整，跳过');
                                }
                            });

                            console.log('从服务器加载的时间安排:', existingSchedules);

                            // 重新初始化时间段显示
                            setTimeout(function () {
                                console.log('重新初始化时间段显示');
                                initTimeSchedules();
                            }, 100);
                        } else {
                            console.log('服务器返回空数据或错误:', response);
                            // 如果服务器也没有数据，添加一个空的时间段
                            existingSchedules = [{ week: '', daytime: '' }];
                            setTimeout(function () {
                                initTimeSchedules();
                            }, 100);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('加载现有时间安排失败:', error);
                    }
                });
            },

            // 异步更新时段占用详情信息
            updateTimeSlotOccupancyInfo: function (ocation, selectedWeek, currentId, $daytimeSelect, existingSchedules, isEdit) {
                console.log('开始异步更新时段占用详情:', {
                    ocation: ocation,
                    selectedWeek: selectedWeek,
                    currentId: currentId,
                    existingSchedules: existingSchedules,
                    isEdit: isEdit
                });

                // 额外调试：检查currentId的获取
                if (isEdit) {
                    console.log('编辑模式 - currentId值:', currentId);
                    if (currentId === 0) {
                        console.warn('警告：编辑模式下currentId为0，可能导致自己占用自己的问题');
                        // 尝试从其他地方获取ID
                        var urlParams = new URLSearchParams(window.location.search);
                        var urlId = urlParams.get('ids');
                        console.log('从URL获取的ID:', urlId);
                    }
                }

                // 如果传入了特定的选择器，只处理该选择器
                if ($daytimeSelect && $daytimeSelect.length > 0) {
                    var $options = $daytimeSelect.find('option');
                    console.log('找到时段选项数量:', $options.length);

                    // 为每个时段选项异步获取详细占用信息
                    $options.each(function () {
                        var $option = $(this);
                        var optionValue = $option.val();

                        // 跳过空选项
                        if (!optionValue) return;

                        // 检查是否已经处理过这个选项
                        if ($option.data('occupancy-checked')) {
                            console.log('时段已检查过，跳过:', optionValue);
                            return;
                        }

                        console.log('检查时段占用:', optionValue);

                        // 标记为已检查
                        $option.data('occupancy-checked', true);

                        // 发送AJAX请求获取详细占用信息
                        $.ajax({
                            url: 'coursetable/classroomeplan/getTimeSlotOccupancy',
                            type: 'POST',
                            data: {
                                ocation_id: ocation,
                                week: selectedWeek,
                                daytime: optionValue,
                                current_id: currentId
                            },
                            success: function (response) {
                                console.log('时段占用检查响应:', optionValue, response);

                                if (response.code === 1 && response.data && response.data.occupied) {
                                    var originalText = $option.text();

                                    // 如果已经包含占用信息，先移除所有可能的占用标记
                                    originalText = originalText.replace(/\(已被.*?\)/, '').replace(/\(当前记录\)/, '').trim();

                                    // 检查是否是当前记录占用
                                    var isCurrentRecordOccupied = false;
                                    if (isEdit && existingSchedules && existingSchedules.length > 0) {
                                        existingSchedules.forEach(function(schedule) {
                                            if (schedule.week === selectedWeek && schedule.daytime === optionValue) {
                                                isCurrentRecordOccupied = true;
                                            }
                                        });
                                    }

                                    var newText;
                                    if (isCurrentRecordOccupied) {
                                        // 如果是当前记录占用，显示"当前记录"
                                        newText = originalText + '(当前记录)';
                                        console.log('当前记录占用:', originalText, '->', newText);
                                        $option.text(newText);
                                        // 当前记录不禁用选择
                                    } else {
                                        // 如果是其他记录占用，显示具体课程信息
                                        var courseName = response.data.course_name || '未知课程';
                                        var className = response.data.class_name || '';
                                        var releaseInfo = response.data.release_info || '';

                                        var occupiedText = '';
                                        if (className) {
                                            occupiedText = '已被【' + courseName + '】-【' + className + '】占用';
                                        } else {
                                            occupiedText = '已被【' + courseName + '】占用';
                                        }

                                        // 添加释放时间信息
                                        if (releaseInfo) {
                                            occupiedText += '，' + releaseInfo;
                                        }

                                        newText = originalText + '(' + occupiedText + ')';

                                        console.log('其他记录占用:', originalText, '->', newText);
                                        $option.text(newText);
                                        $option.prop('disabled', true);
                                    }
                                }
                            },
                            error: function (xhr, status, error) {
                                console.log('获取时段占用详情失败:', optionValue, error);
                            }
                        });
                    });
                } else {
                    // 如果没有传入特定选择器，处理所有相关的选择器
                    $('.time-schedule-item').each(function () {
                        var $item = $(this);
                        var $weekSelect = $item.find('.week-select');
                        var $daytimeSelectItem = $item.find('.daytime-select');

                        // 只处理当前选中周几的时段选择器
                        if ($weekSelect.val() === selectedWeek) {
                            Controller.api.updateTimeSlotOccupancyInfo(ocation, selectedWeek, currentId, $daytimeSelectItem, existingSchedules, isEdit);
                        }
                    });
                }
            },

            // 检查时间冲突
            checkTimeConflict: function () {
                var ocationId = $('#c-ocation_class').val();
                var currentId = 0;

                // 检查是否为编辑模式
                if ($('#row').length > 0) {
                    try {
                        var rowData = JSON.parse($('#row').val());
                        currentId = rowData.id || 0;
                    } catch (e) {
                        currentId = 0;
                    }
                }

                console.log('冲突检测 - 当前记录ID:', currentId);

                if (!ocationId) {
                    return; // 没有选择教室，不检查
                }

                var schedules = [];
                var hasEmpty = false;

                $('.time-schedule-item').each(function () {
                    var week = $(this).find('.week-select').val();
                    var daytime = $(this).find('.daytime-select').val();

                    if (week && daytime) {
                        schedules.push({ week: week, daytime: daytime });
                    } else if (week || daytime) {
                        hasEmpty = true;
                    }
                });

                if (hasEmpty || schedules.length === 0) {
                    return; // 有未完成的时间段，不检查
                }

                // 发送AJAX请求检查冲突
                $.ajax({
                    url: 'coursetable/classroomeplan/checkConflict',
                    type: 'POST',
                    data: {
                        ocation_id: ocationId,
                        schedules: schedules,
                        current_id: currentId
                    },
                    success: function (response) {
                        if (response.code === 1) {
                            // 有冲突，但需要过滤掉当前记录的冲突
                            var filteredConflicts = [];
                            if (response.data && response.data.length > 0) {
                                response.data.forEach(function (conflict) {
                                    // 如果是编辑模式且冲突记录是当前记录，则不显示为冲突
                                    if (!(currentId > 0 && conflict.conflict_id == currentId)) {
                                        filteredConflicts.push(conflict);
                                    }
                                });
                            }

                            if (filteredConflicts.length > 0) {
                                Controller.api.showConflictWarning(filteredConflicts);
                            } else {
                                Controller.api.hideConflictWarning();
                            }
                        } else {
                            // 无冲突
                            Controller.api.hideConflictWarning();
                        }
                    },
                    error: function () {
                        // 请求失败，不显示警告
                        Controller.api.hideConflictWarning();
                    }
                });
            },

            // 显示冲突警告
            showConflictWarning: function (conflicts) {
                // 移除之前的警告
                $('.conflict-warning').remove();

                var warningHtml = '<div class="alert alert-danger conflict-warning" style="margin-top: 10px;">' +
                    '<i class="fa fa-exclamation-triangle"></i> ' +
                    '<strong>教室时间冲突提醒：</strong><br>';

                conflicts.forEach(function (conflict) {
                    warningHtml += '• <strong>' + conflict.week_text + ' ' + conflict.daytime_text + '</strong> (' + conflict.time_range + ') 已被占用<br>';
                    warningHtml += '&nbsp;&nbsp;占用班级：【' + conflict.class_name + '】<br>';
                    if (conflict.course_name) {
                        warningHtml += '&nbsp;&nbsp;占用课程：【' + conflict.course_name + '】<br>';
                    }
                    warningHtml += '&nbsp;&nbsp;冲突时间：' + conflict.conflict_time_range + '<br><br>';
                });

                warningHtml += '<small><i class="fa fa-info-circle"></i> 请选择其他时间段或教室</small>';
                warningHtml += '</div>';

                $('#time-schedule-container').after(warningHtml);

                // 将冲突的时间段选项设为禁用状态
                Controller.api.disableConflictOptions(conflicts);
            },

            // 隐藏冲突警告
            hideConflictWarning: function () {
                $('.conflict-warning').remove();
                // 恢复所有选项的可用状态
                $('.time-schedule-item select option').prop('disabled', false);
            },

            // 禁用冲突的时间段选项
            disableConflictOptions: function (conflicts) {
                var ocationId = $('#c-ocation_class').val();
                if (!ocationId) return;

                // 获取当前记录ID
                var currentId = 0;
                if ($('#row').length > 0) {
                    try {
                        var rowData = JSON.parse($('#row').val());
                        currentId = rowData.id || 0;
                    } catch (e) {
                        currentId = 0;
                    }
                }

                // 先恢复所有选项
                $('.time-schedule-item select option').prop('disabled', false);

                // 禁用冲突的选项（排除当前记录的冲突）
                conflicts.forEach(function (conflict) {
                    // 如果是当前记录的冲突，不禁用
                    if (currentId > 0 && conflict.conflict_id == currentId) {
                        return;
                    }

                    $('.time-schedule-item').each(function () {
                        var $weekSelect = $(this).find('.week-select');
                        var $daytimeSelect = $(this).find('.daytime-select');

                        // 如果周几匹配，禁用对应的时段选项
                        if ($weekSelect.val() === conflict.week) {
                            $daytimeSelect.find('option[value="' + conflict.daytime + '"]').prop('disabled', true);
                        }
                    });
                });
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                status: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="coursetable/classroomeplan/status" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status == 0 || row.status == null ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                changeStatus: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="coursetable/classroomeplan/coursetable/classroomeplan/changeStatus" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status === 0 ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
            }
        }
    };
    return Controller;
});